package com.example.controller;

import com.example.common.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/ai")
public class AIHelperController {

    private static final Logger log = LoggerFactory.getLogger(AIHelperController.class);

    // ✅ 替换为你的 API key 和 URL
    private final String apiKey = "sk-0Q18q1KDGTq35EUZQtlPTLUrIt6qa2D0w1vi8WnPF3CIBnwl";
    private final String apiUrl = "https://tbnx.plus7.plus/v1/chat/completions";

    @PostMapping("/question-helper")
    public Result generateQuestions(@RequestBody Map<String, String> requestBody) {
        String prompt = requestBody.get("prompt");
        log.info("收到AI问卷请求：{}", prompt);

        // 配置超时设置
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setConnectTimeout(5000);
        factory.setReadTimeout(10000);
        RestTemplate restTemplate = new RestTemplate(factory);

        // 构造请求体
        Map<String, Object> payload = new HashMap<>();
        payload.put("model", "deepseek-chat");  // ✅ 使用兼容性更好的模型名

        List<Map<String, String>> messages = new ArrayList<>();
        Map<String, String> messageMap = new HashMap<>();
        messageMap.put("role", "user");
        messageMap.put("content", prompt);
        messages.add(messageMap);
        payload.put("messages", messages);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(apiKey);
        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(payload, headers);

        try {
            log.info("开始调用 AI 接口...");
            ResponseEntity<Map> response = restTemplate.postForEntity(apiUrl, entity, Map.class);

            // ✅ 打印完整返回内容以便排查问题
            log.info("AI 返回响应体：{}", response.getBody());

            if (response.getStatusCode() == HttpStatus.OK) {
                Map<String, Object> body = response.getBody();
                if (body == null) {
                    return Result.error("500", "AI 返回为空");
                }

                List<Map<String, Object>> choices = (List<Map<String, Object>>) body.get("choices");
                if (choices != null && !choices.isEmpty()) {
                    Map<String, Object> msg = (Map<String, Object>) choices.get(0).get("message");
                    String content = (String) msg.get("content");
                    log.info("AI 返回内容：{}", content);
                    return Result.success(content);
                } else {
                    return Result.error("500", "AI 未返回有效内容");
                }
            } else {
                log.error("AI 接口响应异常：{}", response.getStatusCode());
                return Result.error("500", "AI 响应码异常：" + response.getStatusCode());
            }

        } catch (Exception e) {
            log.error("AI 接口调用失败", e);
            return Result.error("500", "AI 接口调用失败：" + e.getMessage());
        }
    }
}
